#ifndef MAP_RENDER_H
#define MAP_RENDER_H

#include <glad/glad.h>

#include <QObject>
#include <QOpenGLFunctions>
#include <QSize>

#include <algorithm/analytical_model/algorithm/cuda/inter_op/Data.h>

// #include <cuda_runtime.h>
// #include <cuda_gl_interop.h>

// static unsigned int VBO, VAO, EBO;
// static float vertices[] = {
//     0.5f,   0.5f,   0.0f,        1.0f, 0.0f, 0.0f,         //右上
//     0.5f,   -0.5f,  0.0f,        0.0f, 1.0f, 0.0f,                 //右下
//     -0.5f,  -0.5f,  0.0f,        0.0f, 0.0f, 1.0f,   //左下
//     -0.5f,  0.5f,   0.0f ,        1.0f, 1.0f, 0.0f   //左上
// };
// static unsigned int indices[] = {
//     0, 1, 2,
//     0, 2, 3         // 按照两个三角形进行render
// };
QT_BEGIN_NAMESPACE
class QQuickWindow;
class QOpenGLShaderProgram;
class QOpenGLTexture;
class QOpenGLBuffer;
QT_END_NAMESPACE

namespace solar
{
    namespace cuda
    {
        class CudaTexture;
    }

    class MapRenderer : public QObject, protected QOpenGLFunctions
    {
            Q_OBJECT
        public:
            MapRenderer();
            ~MapRenderer() override;

            constexpr void setT(qreal t) { t_ = t; }
            constexpr void setViewportSize(const QSize& size) { viewport_size_ = size; }
            constexpr void setWindow(QQuickWindow* window) { window_ = window; }

            constexpr void setX(int x) { x_ = x; }
            constexpr void setY(int y) { y_ = y; }

            constexpr void setVisible(bool visible) { visible_ = visible; }
            constexpr void setResolution(int x, int y)
            {
                img_resolution_x_ = x;
                img_resolution_y_ = y;
            }

            [[nodiscard]] auto getVisible() const -> bool { return visible_; }

        public slots:
            void init();
            void paint();
            void loadTexture();
            void generateTexture(cuda::inter_op::Uchar4* fluxmap_data, cuda::inter_op::Int2 resolution);

            static void reloadTexture() { qDebug() << "maprenderer::reloadTexture"; }

        signals:
            void imageCompleted();

        private:
            QSize viewport_size_;
            QOpenGLShaderProgram* program_;
            QQuickWindow* window_;

            QOpenGLBuffer* vertex_buffer_;
            QOpenGLBuffer* index_buffer_;
            QOpenGLBuffer* color_buffer_;
            QOpenGLBuffer* texcoord_buffer_;

            QOpenGLTexture* texture_; // 纹理，也是要呈现的图像
            // bool run_init;      //init只能运行一次，标记是否已经运行过init

            int x_ = 0;
            int y_ = 0;

            qreal t_ = 0;

            cuda::CudaTexture* cuda_texture_;
            bool visible_ = false;
            bool set_cuda_ = false;

            // uchar4* cuPtr_;
            // cudaGraphicsResource_t resource_;

            int img_resolution_x_; // 图像分辨率
            int img_resolution_y_;

        public:
            bool map_completed_ = false;
    };
} // namespace solar

#endif
